package com.gutsyzhan.yusiailangchain4j.controller;

import com.gutsyzhan.yusiailangchain4j.pojo.MyChatMessage;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mongo")
public class MongoController {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建记录
     */
    @GetMapping("/create")
    public String create(){
        MyChatMessage message = new MyChatMessage();
        message.setId(new ObjectId());
        message.setContent("{\"message\":\"Hello, world!\"}");

        MyChatMessage saveMessage = mongoTemplate.save(message);
        return saveMessage.toString();
    }

    /**
     * 读取记录
     */
    @GetMapping("/read")
    public String read(){
        //假设存在一个id为objectId的记录
        ObjectId id = new ObjectId("68f46b6133a9f889676511a5");
        MyChatMessage readMessage = mongoTemplate.findById(id, MyChatMessage.class);
        return readMessage.toString();
    }

    /**
     * 更新记录
     */
    @GetMapping("/update")
    public String update(){
        //假设存在一个id为objectId的记录
        ObjectId id = new ObjectId("68f46b6133a9f889676511a5");
        MyChatMessage readMessage = mongoTemplate.findById(id, MyChatMessage.class);

        readMessage.setContent("{\"message\":\"Updated content!\"}");

        MyChatMessage updateMessage = mongoTemplate.save(readMessage);
        return updateMessage.toString();
    }

    /**
     * 删除记录
     */
    @GetMapping("/delete")
    public String delete(){
        //假设存在一个id为objectId的记录
        ObjectId id = new ObjectId("68f46b6133a9f889676511a5");
        MyChatMessage readMessage = mongoTemplate.findById(id, MyChatMessage.class);

        if(readMessage != null){
            mongoTemplate.remove(readMessage);
        }
        MyChatMessage deleteMessage = mongoTemplate.findById(id, MyChatMessage.class);
        if(deleteMessage == null){
            return "删除成功";
        }
        return "删除失败";
    }
}
